<?php

namespace App\Http\Controllers\QH_Api;

use App\Http\Controllers\TK_Api\ApiBaseController;
use App\Models\CourseColumn;
use App\Models\GroupBuy;
use App\Models\NetCourse;
use App\Models\Qh_MiniProgramComponent;
use Illuminate\Http\JsonResponse;

class NetCourseController extends ApiBaseController
{
    /**
     * @return JsonResponse|object
     * @throws \RedisException
     * @throws \Exception
     */
    public function getInfo()
    {
        $id = request('id');

        $model = NetCourse::where('id', $id)->first();

        if (!$model) throw new \Exception('网课已下架');

        $valueJsonComponents = $model->components;
        $components = [];
        $componentsSorts = array();
        foreach ($valueJsonComponents as $key => $row) {
            $componentsSorts[$key] = $row['sort'];
        }
        array_multisort($componentsSorts, SORT_ASC, $valueJsonComponents);

        $couponCount = 0;
        foreach ($valueJsonComponents as $component) {
            $c = Qh_MiniProgramComponent::find($component['id']);
            if (!$c) continue;
            $c->data = qhMiniProgramComponentDataFormat($c);
            if (($c->componentName == 'coupon' || $c->componentName == 'document') && $c->data == null) continue;
            if (($c->componentName == 'coupon')) $couponCount += 1;
            $components[] = $c;
        }
        $model->components = $components;
        // 获取优惠券数量
        $model->couponCount = $couponCount;

        // 获取专栏
        $model->courseColumns = CourseColumn::whereIn('id', $model->course_column_ids)
            ->where('is_active', 1)
            ->get();
        // 获取绑定的专栏下的拼团数据
        $model->groupBuy = null;
        //$model->groupBuy = GroupBuy::where('type', 1)
        //    ->whereIn('data_id', $model->courseColumns->pluck('id')->toArray())
        //    ->with(['list' => function ($q) {
        //        $q->select([
        //            'id',
        //            'group_buy_id',
        //            'leader_id',
        //            'leader_avatar',
        //            'leader_nickname',
        //            'original_price',
        //            'leader_price',
        //            'member_price',
        //            'member_num',
        //            'member_count',
        //            'status',
        //            'start_at',
        //            'end_at'
        //        ])
        //            ->where('status', 1)
        //            ->orderByDesc('created_at');
        //    }])
        //    ->first();

        return $this->restful($model);
    }
}
